package com.dormitory.management.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dormitory.management.system.common.res.UserInfoRes;
import com.dormitory.management.system.common.res.UserLoginRes;
import com.dormitory.management.system.entity.User;
import com.dormitory.management.system.enums.UserEnum;
import com.dormitory.management.system.req.UserPageReq;
import com.dormitory.management.system.req.UserUpdateReq;
import com.dormitory.management.system.resp.StuAndHouResp;
import com.dormitory.management.system.resp.UserResp;
import com.dormitory.management.system.utils.FileStoreUtil;
import com.dormitory.management.system.utils.FileUploadUtil;
import com.dormitory.management.system.api.UserApi;
import com.dormitory.management.system.api.UserInfoApi;
import com.dormitory.management.system.api.UserPortraitApi;
import com.dormitory.management.system.mapper.UserMapper;
import com.dormitory.management.system.service.HousemasterService;
import com.dormitory.management.system.service.RoleService;
import com.dormitory.management.system.service.StudentService;
import com.dormitory.management.system.service.UserService;
import com.dormitory.managemnet.util.core.Result;

import com.qiniu.storage.Region;
import com.qiniu.storage.model.DefaultPutRet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("vue-admin-template/user")
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private FileStoreUtil fileStoreUtil;
    @Autowired
    private RoleService roleService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private HousemasterService housemasterService;
    @Resource
    private UserMapper userMapper;
    private UserInfoRes userInfoRes;
    @ApiOperation("用户登录接口")
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public Result<UserLoginRes> login(@RequestBody User user){
        QueryWrapper<UserInfoApi> userLoginResQueryWrapper = new QueryWrapper<>();
        userLoginResQueryWrapper.eq("username",user.getUsername())
                                .isNotNull("username");
        UserInfoApi userInfoApi = userMapper.queryUserInfo(userLoginResQueryWrapper);
        if (userInfoApi==null){
            return Result.error("用户不存在");
        }else {
            if (userInfoApi.getPassword().equals(user.getPassword())){
                userInfoRes=new UserInfoRes();
                String roleKey = userService.getRoleKey(userInfoApi.getUsername());
                userInfoApi.setRoleKey(roleKey);
                if (UserEnum.USER_ADMIN.getRoleKey().equals(roleKey)){
                    userInfoApi.setName(UserEnum.USER_ADMIN.getRoleName());
                    userInfoApi.setRoleName(UserEnum.USER_ADMIN.getRoleName());
                }else if(UserEnum.USER_HOUSEMASTER.getRoleKey().equals(roleKey)){
                    userInfoApi.setName(housemasterService.getById(userInfoApi.getId()).getName());
                    userInfoApi.setRoleName(UserEnum.USER_HOUSEMASTER.getRoleName());
                }else if(UserEnum.USER_STUDENT.getRoleKey().equals(roleKey)){
                    userInfoApi.setName(studentService.getById(userInfoApi.getId()).getName());
                    userInfoApi.setRoleName(UserEnum.USER_STUDENT.getRoleName());
                }
                BeanUtils.copyProperties(userInfoApi,userInfoRes);
                userInfoRes.setRoles(Collections.singletonList(userInfoApi.getRoleKey()));
                return  Result.ok(new UserLoginRes());
            }else return Result.error("密码错误");
        }
    }

    @ApiOperation("获取用户信息接口")
    @RequestMapping(value = "info",method = RequestMethod.GET)
    public Result<UserInfoRes> info(){
        return Result.ok(userInfoRes);
    }

    @ApiOperation("修改用户密码")
    @RequestMapping(value = "UpdateUser",method = RequestMethod.POST)
    public Result<String> UpdateUser(@RequestBody UserApi user){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        User user1 = userService.getOne(queryWrapper);
        if (user1.getPassword().equals(user.getPassword())){
            if (user.getNewPassword().equals(user.getReNewPassword())){
                UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
                userUpdateWrapper.eq("username",user.getUsername()).set("password",user.getReNewPassword());
                boolean flag = userService.update(userUpdateWrapper);
                if (flag){
                    return Result.success("修改成功");
                }else {
                    return Result.error("修改失败");
                }
            }else return Result.error("两次密码输入不相同");

        }else {
            return Result.error("原密码不同");
        }

    }

//    @ApiOperation("修改用户信息接口")
//    @RequestMapping(value = "updateInfo",method = RequestMethod.POST)
//    public Result<String> updateInfo(@RequestBody User user){
//        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
//        userUpdateWrapper.eq("username",user.getUsername()).set("name",user.getName()).set("introduction",user.getIntroduction());
//        boolean flag = userService.update(userUpdateWrapper);
//        if (flag){
//            return Result.success("个人信息修改成功");
//        }else return Result.error("修改失败");
//    }
    @ApiOperation("修改用户头像接口")
    @RequestMapping(value = "updatePortrait",method = RequestMethod.POST)
    public Result<String> updatePortrait(@RequestParam("avatar") MultipartFile avatar) throws IOException {
        InputStream inputStream = avatar.getInputStream();
        String path="D:\\image";
        File savePathDir = new File(path);
        if(!savePathDir.exists()){
            savePathDir.mkdirs();
        }
        File imgFile = new File(path + "\\" + avatar.getOriginalFilename());
        avatar.transferTo(imgFile);
        String upToken = FileUploadUtil.getUploadCredential();
        System.out.println(path + "\\" + avatar.getOriginalFilename());
        DefaultPutRet PutRet = FileUploadUtil.fileUpload(Region.region0(), upToken, path + "\\" + avatar.getOriginalFilename());
//        System.err.println(PutRet);
        String savePath = FileUploadUtil.publicFile(PutRet.key, "r0utmlc4d.hd-bkt.clouddn.com");
        return Result.success("success",savePath);
    }
    @ApiOperation("确认修改头像")
    @RequestMapping(value = "updateing",method = RequestMethod.POST)
    public Result<String> updateing(@RequestBody UserPortraitApi userPortraitApi){
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("username",userPortraitApi.getUsername()).set("avatar",userPortraitApi.getAvatar());
        boolean flag = userService.update(userUpdateWrapper);
        if (flag){
            return Result.ok("修改成功");
        }else return Result.ok("修改失败");
    }

    @ApiOperation("获取用户信息接口")
    @RequestMapping(value = "updateInfo",method = RequestMethod.GET)
    public Result<String> updateInfo(){
        return Result.ok("success");
    }

    @ApiOperation("用户注销接口")
    @RequestMapping(value = "logout",method = RequestMethod.POST)
    public Result<String> logout(){
        userInfoRes=null;
        return Result.success("success");
    }

    @ApiOperation("更新用户")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Result update(@RequestBody UserUpdateReq req){
        if(!userService.update(req)) {
            return Result.error("更新失败！");
        }
        return Result.success("更新成功！");
    }

    @ApiOperation("用户分页列表")
    @RequestMapping(value = "/getPage",method = RequestMethod.POST)
    public Result<IPage<UserResp>> getPage(@RequestBody UserPageReq req){
        return Result.ok(userService.getPage(req));
    }

    @ApiOperation("获取不同角色基本信息")
    @RequestMapping(value = "/getUserInfo/{username}",method = RequestMethod.POST)
    public Result<StuAndHouResp> getUserInfo(@PathVariable String username){
        return Result.ok(userService.getUserInfo(username));
    }
}